package tgc.edu.ljc.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import tgc.edu.ljc.entity.SysRole;
import tgc.edu.ljc.entity.SysUser;
import tgc.edu.ljc.repository.SysUserRepository;


@Component
public class UserUtils {
	@Autowired
	private SysUserRepository userDAO;
	
	public SysUser getUser() {
		try {
			UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String username=userDetails.getUsername();
			/*if("admin".equals(username)) {
				Tea user=new Tea();
				user.setName("开发者");
				user.setUsername("admin");
				SysRole role=new SysRole();
				role.setName("开发者");
				role.setCode("Role_DEVELOPER");
				List<SysRole> roles=new ArrayList<>();
				roles.add(role);
				SysRole role2=new SysRole();
				role2.setName("教师");
				role2.setCode("ROLE_TEACHER");
				roles.add(role2);
				SysRole role3=new SysRole();
				role3.setName("管理员");
				role3.setCode("ROLE_ADMIN");
				roles.add(role3);
				user.setRoles(roles);
				return user;
			}*/
			SysUser user=userDAO.findByUsername(username);
			return user;
		} catch (Exception e) {
			return null;
		}
	}
	
	public boolean hasRole(String roleCode) {
		try {
			List<SysRole> roles=getUser().getRoles();
			List<String> roleCodes=new ArrayList<>();
			for (SysRole sysRole : roles) {
				roleCodes.add(sysRole.getCode());
			}
			return roleCodes.contains(roleCode);
		} catch (Exception e) {
			return false;
		}
	}
	
	public boolean isLogin() {
		return getUser()==null?false:true;
	}
}
